package org.xm.sk.controller;

import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xm.sk.vo.ob.ResultMsg;

import springfox.documentation.annotations.ApiIgnore;

@RestController
public class AppErrorController implements ErrorController {

    public final static String ERROR_PATH = "/error";

    @Autowired
    private MessageSource messages;

    @ApiIgnore()
    @RequestMapping(value = ERROR_PATH)
    public ResultMsg error(HttpServletRequest req,
            HttpServletResponse rsp) {
        Exception e = (Exception) req
                .getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        String mgCode = null;
        if (null != e)
            mgCode = e.getMessage();
        if (null == mgCode && 404 == rsp.getStatus())
            mgCode = messages.getMessage("404", null, "Sorry, Not Found Page",
                    null);
        return new ResultMsg(rsp.getStatus() + "", mgCode, new Date());
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

}